//
//  HSDSpiderDataUploader.m
//  GoldenCard
//
//  Created by 正合适 on 2018/3/22.
//  Copyright © 2018年 合时代. All rights reserved.
//

#import "HSDSpiderDataUploader.h"
#import "HSDSpidermanCache.h"
#import "HSDSpidermanNetworkManager.h"
#import "HSDSpiderMacro.h"
#import <MJExtension/MJExtension.h>
#import "HSDSpidermanPageData.h"
#import "HSDSpidermanPageHelper.h"
#import "HSDResultCacheModel.h"

@interface HSDSpiderDataUploader ()
@property (nonatomic, strong) dispatch_semaphore_t semaphore;
@end

@implementation HSDSpiderDataUploader
- (instancetype)init {
    self = [super init];
    if (self) {
        [self addobservers];
    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)addobservers {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pageRouteEndAction:) name:kPageRouteEndNotify object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startUpload) name:UIApplicationWillEnterForegroundNotification object:nil];
}

- (void)startUpload {
    
    __weak typeof(self) weakself = self;
    NSArray *arr = [[HSDSpidermanCache shareInstance] getAllResultVal];
    for (NSInteger i = 0; i < arr.count; i ++) {
        NSDictionary *dic = arr[i];
        NSString *jsonStr = dic[@"json"];
        //[weakself uploadWithPageJson:jsonStr strategy:UploadStrategy_CacheFirst];
        [self uploadWithResultJson:jsonStr strategy:UploadStrategy_CacheFirst];
    }
}

- (void)pageRouteEndAction:(NSNotification *)notify {
    NSNumber *type = notify.userInfo[@"type"];
    NSString *jsonStr = [notify object];
    // 暂时不区分回到首页的行为结束
//    if (type.integerValue == 1) {
//        [[HSDSpidermanCache shareInstance] insertWithVal:jsonStr];
//    } else {
//        [self uploadWithPageJson:jsonStr strategy:UploadStrategy_UpFirst];
//    }
    //[self uploadWithPageJson:jsonStr strategy:UploadStrategy_UpFirst];
    HSDResultCacheModel *model = [HSDResultCacheModel new];
    model.headerJsonStr = _baseInfo.mj_JSONString;
    
    HSDSpidermanPageData *data = [HSDSpidermanPageData mj_objectWithKeyValues:jsonStr];
    data.networkinfo = _networkInfoModel;
    data.networkinfo.latitude = _locationModel.latitude;
    data.networkinfo.longitude = _locationModel.longitude;
    data.custom = _customModel;
    model.bodyJsonStr = data.mj_JSONString;
    [self uploadWithResultJson:model.mj_JSONString strategy:UploadStrategy_UpFirst];
}

- (NSDictionary *)paramsWithJsonStr:(NSString *)jsonStr {
    HSDSpidermanPageData *data = [HSDSpidermanPageData mj_objectWithKeyValues:jsonStr];
    data.networkinfo = _networkInfoModel;
    data.networkinfo.latitude = _locationModel.latitude;
    data.networkinfo.longitude = _locationModel.longitude;
    data.custom = _customModel;
    return [data mj_keyValues];
}

- (void)uploadWithResultJson:(NSString *)json strategy:(UploadStrategy)strategy {
    HSDResultCacheModel *cacheModel = [HSDResultCacheModel mj_objectWithKeyValues:json];
    if (!_networkInfoModel.wifi.boolValue) {
        if (strategy == UploadStrategy_UpFirst) {
            //[[HSDSpidermanCache shareInstance] insertWithVal:json];
            [[HSDSpidermanCache shareInstance] insertResultWithVal:json];
        }
        return;
    }
//    __weak typeof(self) weakself = self;
    NSMutableString *muS = [NSMutableString stringWithString:json];
//    NSDictionary *param = [self paramsWithJsonStr:json];
    
    HSDSpidermanPageData *bodyData = [HSDSpidermanPageData mj_objectWithKeyValues:cacheModel.bodyJsonStr];
    [[HSDSpidermanNetworkManager instance] requestWithType:RequestType_Post url:kUploadDataApi params:bodyData.mj_keyValues header:@{@"data_head":cacheModel.headerJsonStr} success:^(id responseObj) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
#ifdef DEBUG
            NSLog(@"HSDSpiderman_Upload_Log => \n header: %@ \n body: %@",cacheModel.headerJsonStr,cacheModel.bodyJsonStr);
#endif
            if (strategy == UploadStrategy_CacheFirst) {
                [[HSDSpidermanCache shareInstance] deleteResultValWithVal:muS];
            }
        });
    } error:^(id responseObj) {
        // 失败就缓存数据
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //if (strategy == UploadStrategy_UpFirst) [[HSDSpidermanCache shareInstance] insertWithVal:muS];
            if (strategy == UploadStrategy_UpFirst) {
                [[HSDSpidermanCache shareInstance] insertResultWithVal:muS];
            }
        });
    }];
}

/*
- (void)uploadWithPageJson:(NSString *)json strategy:(UploadStrategy)strategy {
    if (!_networkInfoModel.wifi.boolValue) {
        if (strategy == UploadStrategy_UpFirst) {
            [[HSDSpidermanCache shareInstance] insertWithVal:json];
        }
        return;
    }
    __weak typeof(self) weakself = self;
    NSMutableString *muS = [NSMutableString stringWithString:json];
    NSDictionary *param = [self paramsWithJsonStr:json];
    [[HSDSpidermanNetworkManager instance] requestWithType:RequestType_Post url:kUploadDataApi params:param header:@{@"data_head":_baseInfo.mj_JSONString} success:^(id responseObj) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            if (strategy == UploadStrategy_CacheFirst) {
                [[HSDSpidermanCache shareInstance] deletePageValWithVal:muS];
            }
        });
    } error:^(id responseObj) {
        // 失败就缓存数据
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            if (strategy == UploadStrategy_UpFirst) [[HSDSpidermanCache shareInstance] insertWithVal:muS];
        });
    }];
}
*/
@end
